package com.paratice.zookeeper;

import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class WatcherDemo {
	
	public static void main(String[] args) {
		try {
			CountDownLatch countDownLatch = new CountDownLatch(1);
			ZooKeeper zookeeper = new ZooKeeper("192.168.2.200:2181", 4000, new Watcher() {
				
				@Override
				public void process(WatchedEvent event) {
					System.out.println("默认事件：" + event.getType());
					if (Event.KeeperState.SyncConnected == event.getState()) {
						countDownLatch.countDown();
					}
				}
			});
			countDownLatch.await();
			
			zookeeper.create("/zk-persis", "1".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
		
			Stat stat = zookeeper.exists("/zk-persis", new Watcher() {
				@Override
				public void process(WatchedEvent event) {
					System.out.println(event.getType() + " -> " + event.getPath());
				}
			});
			
			zookeeper.setData("/zk-persis", "2".getBytes(), stat.getVersion());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
